<?php
/**
 * Created by PhpStorm.
 * User: yzr
 * Date: 2/2/2021
 * Time: 21:14
 */
namespace app\api\controller\wap;
use app\common\model\users\AccountLevelLimit;
use app\common\model\users\Wallet;
use mall\utils\Tool;
use think\facade\Db;
use think\facade\Request;


/**
 * 我的等级相关
 * Class Level
 * @package app\api\controller\wap
 */
class Level extends Base
{


    /**
     * 获取我的等级
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function fetch(){
        try{
            $result = [
                'issueList' => [],
                'acceptList'    => [],
            ];
            $accountLevelLimitModel = new AccountLevelLimit();
            $details = $accountLevelLimitModel->findByUserId(\mall\basic\Users::get('id'));
            $issueList = $accountLevelLimitModel->getIssueLevelDetails();

            foreach($issueList as $value) {
                $result['issueList'][] = [
                    'name'  => $value['name'],
                    'limits'  => $value['limits'] - 0,
                    'amount'  => $value['amount'] - 0,
                    'level_id'  => $value['level_id'] - 0,
                    'current'  => $value['level_id'] == $details['issue_level']?true:false,
                ];
            }
            $acceptList = $accountLevelLimitModel->getAcceptLevelDetails();
            foreach($acceptList as $value) {
                $result['acceptList'][] = [
                    'name'  => $value['name'],
                    'min'   => 0,
                    'max'   => $value['limits'] - 0,
                    'amount'  => $value['amount'] - 0,
                    'level_id'  => $value['level_id'] - 0,
                    'current'  => $value['level_id'] == $details['accept_level']?true:false,
                ];
            }
        }catch (\Exception $e) {
            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }
        return $this->returnAjax("ok",1,$result);
    }

    /**
     * 购买发布等级
     */
    public function issueBuy(){
        return $this->buy('issue');
    }

    /**
     * 购买接单等级
     */
    public function acceptBuy(){
        return $this->buy('accept');
    }

    /**
     * 统一购买等级
     * @param $type
     */
    private function buy($type){
        $params = array_map(function($value){return trim($value);},Request::post());
        try{
            // 验证数据
            validate([
                'current'   => 'require|integer|>:0',
                'buy'   => 'require|integer|>:0',
                'amount'  => 'require|float|>:0',
            ],[
                'current'   =>  '请填写正确的当前等级',
                'buy'   =>  '请填写正确的购买等级',
                'amount'   =>  '请填写正确的购买金额',
            ])->check($params);

            // 获取当前等级
            $accountLevelLimit = new AccountLevelLimit();
            if(!$accountLevelDetails = $accountLevelLimit->findByUserId(\mall\basic\Users::get('id'))) {
                throw new \Exception('数据错误');
            }
            if($params['current'] != $accountLevelDetails[$type . '_level']) {
                throw new \Exception('当前等级错误，请刷新重试');
            }

            /********* 获取并判断升级所需要金额 ***********/
            $callMethod = 'get' . (strtoupper($type[0])) . substr($type,1) . 'LevelDetails';
            $levelList = call_user_func_array([$accountLevelLimit,$callMethod],[]);
            $amount = 0;
            $startCount = false;
            $isClose = false;
            foreach($levelList as $value) {
                if($value['level_id'] == $params['current']) {
                    $startCount = true;
                    continue;
                }
                if($startCount) {
                    $amount = bcadd($amount,$value['amount'],2);
                    if($value['level_id'] == $params['buy']) {
                        $isClose = true;
                        break;
                    }
                }
            }
            if(!$isClose) {
                throw new \Exception('当前或购买等级有误');
            }
            if(bccomp($amount,$params['amount']) != 0) {
                throw new \Exception('购买金额计算有误');
            }
            /******* END 获取并判断升级所需要金额 *********/

            // 获取余额
            $walletModel = new Wallet();
            $walletDetails = $walletModel->findOne(\mall\basic\Users::get('id'));
            if(bccomp($params['amount'],$walletModel->getBalanceCount($walletDetails),2) == 1) {
                throw new \Exception('您的余额不足以购买该等级');
            }
            Db::startTrans();
            $accountLevelLimit->buy($accountLevelDetails,$walletDetails,$params['buy'],$params['amount'],$type);
            Db::commit();
        }catch (\Exception $e) {
            Db::rollback();

            return $this->returnAjax(Tool::getErrorMessage($e),0);
        }
        return $this->returnAjax("等级购买成功",1,[]);
    }
}
